package com.gz.mylife.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.app.llopendoor.FagmentOpenDoor;
import com.gz.mylife.im.MessageChannel;
import com.gz.mylife.im.Session;
import com.gz.mylife.im.MessageChannel.Meta;
import com.gz.mylife.util.ToastUtils;
import com.zl.smartmall.library.IGZAddress;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.Tools;

public class Plaza extends BaseActivity implements OnPageChangeListener,
OnClickListener, Observer {

	private static final String TAG = Plaza.class.getSimpleName();

	private int[] mMenuDefaultRec;
	private int[] mMenuSelectedRec;
	private int mCurrentMenu;
	private long mBackKeyPressedTime;
	private String[] mPageTitles;
	private AutoRefreshReceiver mAutoRefreshReceiver;
	private FragmentAdapter mFragmentAdapter;

	private ImageView[] mIvMenu;
	private TextView mTvUnreadIMCount;
	private ViewPager mViewPager;

	private boolean unbind;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_plaza);
		MessageChannel.get().register(MessageChannel.SESSION, this);

		mMenuDefaultRec = new int[] { R.drawable.ic_menu_mall_default,
				R.drawable.ic_menu_participation_default,
				R.drawable.ic_menu_opendoor_default,
				R.drawable.ic_menu_shopping_cart_default,
				R.drawable.ic_menu_personal_default,
		};

		mMenuSelectedRec = new int[] { R.drawable.ic_menu_mall_selected,
				R.drawable.ic_menu_participation_selected,
				R.drawable.ic_menu_opendoor_selected,
				R.drawable.ic_menu_shopping_cart_selected,
				R.drawable.ic_menu_personal_selected,
		};

		mPageTitles = new String[] {
				PreferenceModel.getString(
						Constants.PREFERENCE_KEY_COMMUNITY_NAME, "双明汇"),"参与","考拉开门",
						"购物车", "个人中心" };

		mAutoRefreshReceiver = new AutoRefreshReceiver();
		IntentFilter intentfilt = new IntentFilter(Constants.ACTION_CHANGE_COMMUNITY);
		registerReceiver(mAutoRefreshReceiver, intentfilt);
		IntentFilter intentFilter = new IntentFilter("CHANCE_PLAZA_TITLE");
		registerReceiver(mAutoRefreshReceiver, intentFilter);
		setActionbarTitle(mPageTitles[0], true);
		setActionbarTitleCompoundDrawable(0);

		mFragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mViewPager.setAdapter(mFragmentAdapter);
		mViewPager.setOnPageChangeListener(this);
		mViewPager.setOffscreenPageLimit(5);

		mIvMenu = new ImageView[] {
				(ImageView) findViewById(R.id.iv_menu_mall),
				(ImageView) findViewById(R.id.iv_menu_participation),
				(ImageView) findViewById(R.id.iv_menu_opendoor),
				(ImageView) findViewById(R.id.iv_menu_shopping_cart),
				(ImageView) findViewById(R.id.iv_menu_personal)
		};

		View menu = findViewById(R.id.layout_menu_mall);
		menu.setTag(0);
		menu.setOnClickListener(this);
		menu = findViewById(R.id.layout_menu_participation);
		menu.setTag(1);
		menu.setOnClickListener(this);
		menu = findViewById(R.id.layout_menu_opendoor);
		menu.setTag(2);
		menu.setOnClickListener(this);
		menu = findViewById(R.id.layout_menu_shopping_cart);
		menu.setTag(3);
		menu.setOnClickListener(this);
		menu = findViewById(R.id.layout_menu_personal);
		menu.setTag(4);
		menu.setOnClickListener(this);

		unbind = getIntent().getBooleanExtra("unBind", false);

		if (IGZAddress.getInstance().getCurrentCommunityID() == -1 && !unbind) {
			Intent intent = new Intent(getApplicationContext(),
					BindCommunityAcivity.class);
			intent.putExtra("unbind", true);
			startActivity(intent);
			finish();
		}
		int position = getIntent().getIntExtra("page_index", 0);
		selectPager(position);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.plaza, menu);
		View messageView = MenuItemCompat.getActionView(menu
				.findItem(R.id.action_message));
		messageView.setOnClickListener(this);
		mTvUnreadIMCount = (TextView) messageView
				.findViewById(R.id.tv_unread_im_count);
		checkHasUnreadMessage();
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mAutoRefreshReceiver);
		MessageChannel.get().unregister(MessageChannel.SESSION, this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		CrashHandler.d(TAG, TAG + " onNewIntent");
		int position = intent.getIntExtra("page_index", 0);
		selectPager(position);
	}

	private void selectPager(int position) {
		changeMenu(position);
		setActionbarTitle(mPageTitles[position], true);
		setActionbarTitleCompoundDrawable(position);
		mViewPager.setCurrentItem(position, false);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		if (mViewPager.getCurrentItem() == 2) {
			// MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_message),
			// MenuItemCompat.SHOW_AS_ACTION_NEVER);
		} else {
			MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_message),
					MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - mBackKeyPressedTime) > 1000) {
				ToastUtils.showToast(this, "再按一次退出程序", Toast.LENGTH_SHORT);
				mBackKeyPressedTime = System.currentTimeMillis();

			} else {
				this.finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub
		changeMenu(position);
		// mActionBar.setTitle(mPageTitles[position]);
		setActionbarTitle(mPageTitles[position], true);
		setActionbarTitleCompoundDrawable(position);
		// invalidateOptionsMenu();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.layout_menu_mall:
		case R.id.layout_menu_participation:
		case R.id.layout_menu_opendoor:
		case R.id.layout_menu_personal:
		case R.id.layout_menu_shopping_cart:
			if (mCurrentMenu != (Integer) v.getTag())
				// changeMenu((Integer) v.getTag());
				mViewPager.setCurrentItem((Integer) v.getTag(), false);
			break;

		case R.id.action_view_message:
			mTvUnreadIMCount.setVisibility(View.GONE);
			// PreferenceModel.putInt(PreferenceModel.unread_count_sms, 0);
			startActivity(new Intent(getApplicationContext(), Session.class));
			break;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		checkHasUnreadMessage();
	}

	private void changeMenu(int position) {
		// TODO Auto-generated method stub
		mIvMenu[mCurrentMenu].setImageResource(mMenuDefaultRec[mCurrentMenu]);
		mIvMenu[position].setImageResource(mMenuSelectedRec[position]);
		mCurrentMenu = position;
	}

	private void checkHasUnreadMessage() {
		int unReadChat = PreferenceModel.getInt(
				Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
		if (mTvUnreadIMCount != null) {
			if (unReadChat > 0) {
				mTvUnreadIMCount.setVisibility(View.VISIBLE);
				if (unReadChat > 9) {
					mTvUnreadIMCount.setText("9+");
				} else {
					mTvUnreadIMCount.setText("" + unReadChat);
				}
			} else {
				mTvUnreadIMCount.setVisibility(View.GONE);
			}
		}
	}

	private void setActionbarTitleCompoundDrawable(int position) {
		if (position == 0) {
			mActionbarTitle.setCompoundDrawablesWithIntrinsicBounds(null, null,
					getResources().getDrawable(R.drawable.ic_mall_down_arrow),
					null);
			mActionbarTitle.setCompoundDrawablePadding(Tools.dip2px(
					getApplicationContext(), 10));
		} else if(position == 1){

		}else {
			mActionbarTitle.setCompoundDrawablesWithIntrinsicBounds(null, null,
					null, null);
		}
	}

	private class AutoRefreshReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			mPageTitles[0] = IGZAddress.getInstance().getCurrentCommunityName();
			if (mViewPager.getCurrentItem() == 0) {
				setActionbarTitle(mPageTitles[0], true);
			}
			((FragmentMall) mFragmentAdapter.getItem(0)).autoRefresh();// 刷新商城
			((FragmentShoppingCart) mFragmentAdapter.getItem(2)).autoRefresh();// 刷新商城
			((FragmentParticipation) mFragmentAdapter.getItem(1)).autoRefresh();// 刷新商城
		}

	}

	public static class FragmentAdapter extends FragmentPagerAdapter {

		private List<Fragment> mFragments;

		public FragmentAdapter(FragmentManager fm) {
			super(fm);
			mFragments = new ArrayList<Fragment>();
			mFragments.add(new FragmentMall());// 商城
			mFragments.add(new FragmentParticipation());// 参与
			mFragments.add(new FagmentOpenDoor());//门禁
			mFragments.add(new FragmentShoppingCart());// 购物车
			mFragments.add(new FragmentPersonal());// 个人中心

		}

		@Override
		public Fragment getItem(int position) {
			return mFragments.get(position);
		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			super.destroyItem(container, position, object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {

			Object obj = super.instantiateItem(container, position);
			CrashHandler.d(TAG, "FragmentAdapter's instantiateItem");
			return obj;
		}

	}

	@Override
	public void update(Observable arg0, Object data) {
		Meta meta = (Meta) data;
		if (meta.msgType == MessageChannel.SESSION) {
			checkHasUnreadMessage();
		}
	}

}
